package com.fulihui.wgj.service.labels;

import com.alibaba.dubbo.config.annotation.Service;
import com.fulihui.common.builder.rpc.RpcResultBuilder;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.error.Errors;
import com.fulihui.common.error.InvokeServiceException;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.util.ConditionValidator;
import com.fulihui.wgj.dal.mybatis.domain.LabelsInfo;
import com.fulihui.wgj.dal.mybatis.repository.LabelsInfoRepository;
import com.fulihui.wgj.facade.dto.LabelsInfoDTO;
import com.fulihui.wgj.facade.request.labels.QrcodeLabelSaveRequest;
import com.fulihui.wgj.facade.service.labels.LabelInfoService;
import com.fulihui.wgj.service.material.WxMaterialServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

import static com.fulihui.common.error.Errors.Commons.SAVE_FAILED;

@Component
@Service(interfaceClass = LabelInfoService.class, version = "1.0.0")
public class LabelInfoServiceImpl implements LabelInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxMaterialServiceImpl.class);

    @Autowired
    private LabelsInfoRepository labelsInfoRepository;

    @Override
    public SimpleResult<List<LabelsInfoDTO>> queryAll() {
        List<LabelsInfo> labelsInfos = labelsInfoRepository.queryAll();
        List<LabelsInfoDTO> infoDTOS = null;
        if (!CollectionUtils.isEmpty(labelsInfos)) {
            infoDTOS = BeanConv.copy(labelsInfos, LabelsInfoDTO.class);
        }
        return RpcResultBuilder.succSimple(infoDTOS);
    }

    @Override
    public SimpleResult<String> save(QrcodeLabelSaveRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);

        Example example = new Example(LabelsInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("labelName", request.getLabelName());
        List<LabelsInfo> labelsInfos = labelsInfoRepository.queryByExample(example);
        if (!CollectionUtils.isEmpty(labelsInfos)) {
            return RpcResultBuilder.failSimple(Errors.Commons.RECORD_ALREADY_EXISTS);
        }

        //TODO 此处部分参数固定，后期扩展再新建枚举维护
        LabelsInfo labelsInfo = new LabelsInfo();
        labelsInfo.setLabelName(request.getLabelName());
        labelsInfo.setWeight(100);
        labelsInfo.setUpdateTime(new Date());
        labelsInfo.setCreateTime(new Date());
        labelsInfo.setChannelCode("FLHQRC");
        Integer resultCount = labelsInfoRepository.saveSelective(labelsInfo);
        return resultCount > 0 ? RpcResultBuilder.succSimple(String.valueOf(labelsInfo.getLabelId())) : RpcResultBuilder.failSimple(SAVE_FAILED);
    }
}
